/*
 * desc: 描述
 * Author: jayafs
 * Email: 1169655050@qq.com
 * Date: 2020-11-25 22:11:40
 * LastEditors: Please set LastEditors
 * LastEditTime: 2020-11-26 10:12:56
 */
import { useEffect } from 'react';
import { isEmpty } from 'project-libs';
let observer: IntersectionObserver;
export default function useImgHooks(
  ele: string,
  callback?: (arg: IntersectionObserverEntry[]) => void,
  watch?: any[],
) {
  useEffect(() => {
    const nodes = document.querySelectorAll(ele);
    if (!isEmpty(nodes)) {
      observer = new IntersectionObserver(entries => {
        callback && callback(entries);
        entries.forEach(item => {
          if (item.isIntersecting) {
            const dataSrc = item.target.getAttribute('data-src') || '';
            item.target.setAttribute('src', dataSrc);
            observer.unobserve(item.target);
          }
        });
      });
      nodes.forEach(item => {
        observer.observe(item);
      });
    }

    return () => {
      if (!isEmpty(nodes)) {
        observer.disconnect();
      }
    };
  });
}
